package com.interest.plus2.net;


import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 拦截器
 */
public class HttpCommonInterceptor implements Interceptor {

    private Map<String, String> mHeaderParamsMap = new HashMap<>();

    public HttpCommonInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // 新的请求
        Request.Builder requestBuilder = request.newBuilder();
        //requestBuilder.method(oldRequest.method(), oldRequest.body());

        //添加公共参数,添加到header中
//        requestBuilder.header("sid", String.valueOf(DeviceInfo.getInstance(ApplicationData.mApplication).getsid()));
//        requestBuilder.header("ssid", DeviceInfo.getInstance(ApplicationData.mApplication).getssid());
//        if (UserinfoUtils.getInstance().getLogined() == 2) {
//            requestBuilder.header("token", DeviceInfo.getInstance(ApplicationData.mApplication).getToken());
//            requestBuilder.header("memcard", DeviceInfo.getInstance(ApplicationData.mApplication).getMemcard());
//        } else {
//            requestBuilder.header("token", "");
//            requestBuilder.header("memcard", "");
//        }
        if (mHeaderParamsMap.size() > 0) {
            for (Map.Entry<String, String> params : mHeaderParamsMap.entrySet()) {
                requestBuilder.header(params.getKey(), params.getValue());
            }
        }
        request = requestBuilder.build();
        return chain.proceed(request);
    }

    public static class Builder {
        HttpCommonInterceptor mHttpCommonInterceptor;

        public Builder() {
            mHttpCommonInterceptor = new HttpCommonInterceptor();
        }

        public Builder addHeaderParams(String key, String value) {
            mHttpCommonInterceptor.mHeaderParamsMap.put(key, value);
            return this;
        }

        public Builder addHeaderParams(String key, int value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, float value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, long value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, double value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public HttpCommonInterceptor build() {
            return mHttpCommonInterceptor;
        }

    }
}
